package net.sf.cldsql.sql2json.main;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;

import net.sf.cldsql.dj.mvc.DiServiceImpl;
import net.sf.cldsql.dj.mvc.DiContext;
import net.sf.cldsql.dj.utl.DiException;
import net.sf.cldsql.dj.utl.StrUtl;
import net.sf.cldsql.sql2json.sql.JsonBuilder;
import net.sf.cldsql.sql2json.sql.SqlRestQuery;

/**
 * Sql2JsonService
 */
public class SjSqlServiceImpl extends DiServiceImpl implements SjSqlService {
    
    /** @param args
    /** @return */
    public Object execute (final DiContext context, final String... args) {
        try {
            //DiContext context = (DiContext)args[0];
            log.debug("start");
            
            String sql = context.getParam("sql");
            log.debug(new StrUtl().flattenCrLf(sql));
            PreparedStatement stmt;
            stmt = conn.getConn().prepareStatement(sql.toString());
            StringBuilder jsonBuf;
            if (stmt.execute()) {
                ResultSet rset = null;
                SjConf conf = container.<SjConf>get(SjConf.class);
                jsonBuf = JsonBuilder.get().convResultSetToJson((rset = stmt.getResultSet()), Integer.parseInt(conf.get("sql.fetch_limit")));
                if (rset != null) {
                    rset.close();
                }
                stmt.close();
            } else {
                stmt.close();
                jsonBuf = new StringBuilder ("{\"status\":0}");
            }
            
            log.debug("finished with result: {}.", jsonBuf);
            return jsonBuf;
        } catch (SQLException e) {
            throw new DiException(e);
        }
    }

}
